package com.xc.hotelmgr.datapusherali.sdk;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;

import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @Auther dy
 * @date 2020/7/31 11:59
 */
public class FzSdk {

    // 签名
    private static String sign(String secret, JSONObject data) {

        Set<String> keySet= data.keySet();
        List<String> keyList = new ArrayList<String>(keySet);
        Collections.sort(keyList);
        StringBuilder sb = new StringBuilder();
        for (String key:keyList) {
            String strKV = key + data.get(key);
            sb.append(strKV);
        }
        return SecureUtil.md5(secret + sb + secret).toUpperCase();
    }

    //公共请求参数
    private static JSONObject commonData(String appKey, String session, String method, JSONObject jsonData) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("method", method);
        jsonObject.put("app_key", appKey);
        jsonObject.put("session", session);
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = df.format(new Date());
        jsonObject.put("timestamp", date);
        String format = "json";
        jsonObject.put("format", format);
        String version = "2.0";
        jsonObject.put("v", version);
        String signMethod = "md5";
        jsonObject.put("sign_method", signMethod);
        JSONObject jsonObjectAll = new JSONObject();
        jsonObjectAll.putAll(jsonData);
        jsonObjectAll.putAll(jsonObject);
        return jsonObjectAll;
    }

    // post
    public static String req(String method, JSONObject jsonObject) {
        String secret = (String) jsonObject.remove("secret");
        String appKey = (String) jsonObject.remove("appKey");
        String session  = (String) jsonObject.remove("sessionKey");
        JSONObject data = commonData(appKey, session, method, jsonObject);
        String sign = sign(secret, data);
        data.put("sign", sign);
        String url = "https://eco.taobao.com/router/rest";
        return HttpRequest.post(url).timeout(100000).form(data).timeout(100000).execute().body();
    }
}
